class Solution{
public:
  ListNode *addTwoNumbers(ListNode *l1, ListNode *l2){

    ListNode *p1 = l1;
    ListNode *p2 = l2;
    ListNode *res = new ListNode;
    ListNode *p = res;
    // 进位变量f，用来表示这一位是否发生进位
    int f = 0;

    while(p1 != nullptr || p2 != nullptr || f != 0){
      ListNode *temp = new ListNode(0, p->next);
      temp->val += f;

      if(p1 != nullptr){
        temp->val += p1->val;
        p1 = p1->next;
      }

      if(p2 != nullptr){
        temp->val += p2->val;
        p2 = p2->next;
      }

      if(temp->val >= 10){
        f = 1;
      }else{
        f = 0;
      }

      temp->val %= 10;
      p->next = temp;
      p = p->next;

    }

    return res->next;

  }
};